package com.yt.base.service.impl;

import java.util.List;
import java.util.Map;

import com.yt.base.model.AclGroup;
import com.yt.base.service.AclGroupOperationService;
import com.yt.core.service.GenericServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yt.base.dao.AclGroupOperationDao;
import com.yt.base.model.AclGroupOperation;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class AclGroupOperationServiceImpl extends GenericServiceImpl<AclGroupOperation, Long> implements
		AclGroupOperationService {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	private AclGroupOperationDao dao;
	
	public AclGroupOperationServiceImpl(AclGroupOperationDao dao) {
		super(dao);
		this.dao = dao;
	}

	@Override
	public List<AclGroupOperation> findByGroup(Long groupId) {
		return dao.findByGroup(groupId);
	}
	
	@Override
	public void modify(AclGroup group, List<String> aclList) {
		logger.debug("更新用户组权限：{}", group.getName());
		long groupId = group.getId();
		
		List<AclGroupOperation> dbOpList = findByGroup(groupId);
		Map<String, Long> dbOpMap = Maps.newHashMap();
		for (AclGroupOperation op : dbOpList) {
			String key = Joiner.on('_').appendTo(new StringBuilder(),
					new Long[] { op.getCategoryId(), op.getPrivilegeId(), op.getOperationId() })
					.toString();
			dbOpMap.put(key, op.getId());
		}
		
		List<AclGroupOperation> insertList = Lists.newArrayList();
		List<Long> removeList = Lists.newArrayList();
		Splitter splitter = Splitter.on('_').trimResults();
		for (String acl : aclList) {
			if (dbOpMap.containsKey(acl)) {
				dbOpMap.remove(acl);
			} else {
				List<String> segList = splitter.splitToList(acl);
				if (segList.size() == 3) {
					AclGroupOperation op = new AclGroupOperation(groupId, Long.valueOf(segList.get(0)),
							Long.valueOf(segList.get(1)), Long.valueOf(segList.get(2)));
					insertList.add(op);
				}
			}
		}
		removeList.addAll(dbOpMap.values());
		
		batchInsert(insertList);
		batchDelete(removeList);
	}
	
	@Override
	public void batchDelete(List<Long> idList) {
		if (idList != null && !idList.isEmpty()) {
			int n = dao.batchDelete(idList);
			logger.debug("预计删除{}, 实际删除{}", idList.size(), n);
		}
	}
	
	@Override
	public void batchInsert(List<AclGroupOperation> opList) {
		if (opList != null && !opList.isEmpty()) {
			int n = dao.batchInsert(opList);
			logger.debug("预计插入{}, 实际插入{}", opList.size(), n);
		}
	}
}
